#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

unsigned long GetLength(const char * file_path,int bIsAsccii){
	unsigned long size;
	FILE * hFile;
	if(bIsAsccii)
		hFile = fopen(file_path,"r");
	else
		hFile = fopen(file_path,"rb");
	fseek(hFile,0,SEEK_END);
	size = ftell(hFile);
	fclose(hFile);
	return size;
}

int main(int argc, char *argv[])
{
	char name_buf[100] = {0};
	unsigned long split_size = 0, size = 0,size_left = 0;
	FILE * hFile = 0, *hDestFile = 0;
	unsigned char *buffer = 0;
	int nCount,num,nStartPos = 0,bIsAsccii = 0;
	long nPos;
	if(argc >= 3){
		if(argv[1][0] == '\\' && toupper(argv[1][1]) == 'A'){
			nStartPos = bIsAsccii = 1;
		}
		if(isdigit(argv[2 + nStartPos][1]) && argv[2 + nStartPos][0] == '\\'){
			num = argv[2][1] - '0';
		}else if(argv[1][0] == '\\' && toupper(argv[1][1]) == 'H'){
			if(argc != 4){
				printf("The syntax of the command is incorrect.\n");
				return EXIT_FAILURE;
			}
			sprintf(name_buf,"splith %s %s",argv[2],argv[3]);
			system(name_buf);
			return 0;
		}else{
			num = argc - 2 - nStartPos;
		}
		size = size_left = GetLength(argv[1 + nStartPos],bIsAsccii);
		printf("size:%ld\n",size);
		split_size = size/num + 2;
		buffer = (unsigned char *)malloc(split_size);
		if(bIsAsccii)
			hFile = fopen(argv[1 + nStartPos],"r");
		else 
			hFile = fopen(argv[1 + nStartPos],"rb");
		for(nPos = nCount = 0;nCount != num;nCount++,nPos = nPos + split_size){
			printf("%ld\n",split_size);
			if((size_left - split_size) > size_left + split_size){
				split_size = size_left;
			}else{
				size_left -= split_size;
			}
			fseek(hFile,nPos,SEEK_SET);
			fread(buffer,sizeof(unsigned char),split_size,hFile);
			fclose(hDestFile);
			if(isdigit(argv[2 + nStartPos][1]) && argv[2 + nStartPos][0] == '\\'){
				sprintf(name_buf,"%s.split.part%d",argv[1 + nStartPos],nCount + 1 + nStartPos);
				if(bIsAsccii)
					hDestFile = fopen(name_buf,"w");
				else
					hDestFile = fopen(name_buf,"wb");
				printf("Part %s (%ld) created\n",name_buf,split_size);
			}else{
				printf("File:%s\n",argv[2 + nCount + nStartPos]);
				if(bIsAsccii)
					hDestFile = fopen(argv[2 + nCount + nStartPos],"w");
				else
					hDestFile = fopen(argv[2 + nCount + nStartPos],"wb");
				printf("Part %s (%ld) created\n",argv[2 + nCount + nStartPos],split_size);
			}
			fwrite(buffer,sizeof(unsigned char),split_size,hDestFile);
			fclose(hDestFile);
		}
		printf("%d Parts created.\n",num);
	}else{
		printf(
		"The syntax of the command is incorrect.\n"
		"split [\\A] <source> <destination> <destination> [more]\n"
		"split [\\A] <source> \\<number>\n"
		"split \\H <source name> <split number>\n"
		);
	}
	free(buffer);
	return 0;
}
